﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.Utils;
using System.Threading;
using HostAssistantCore;
using HostAssistantBLL;
using System.Text.RegularExpressions;

namespace HostAssistant
{
    public partial class sitelist : U1UserControl
    {
        public sitelist()
        {
            InitializeComponent();

            //   Convert.ToInt32("weqew");
            //  this.gridView1.RowClick += new DevExpress.XtraGrid.Views.Grid.RowClickEventHandler(gridView1_RowClick);

        }
        void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Right)
                return;
            int hand = gridView1.FocusedRowHandle;
            DataRow drCurrent = gridView1.GetDataRow(hand);
            DialogResult dialogResult = MessageBox.Show("是否删除该记录？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (dialogResult == DialogResult.OK)
            {
                MessageBox.Show(drCurrent["ID"].ToString());
                //Presenter.DelAppSystem();
                //  this.gridControl1.DataSource = null;
                //  this.gridControl1.DataSource = Presenter.dt;
            }
            else
            {
                return;
            }

        }

        private void sitelist_Load(object sender, EventArgs e)
        {
            //  labelControl1.Text = DateTime.Now.ToString();


            TextBoxToolV2.SetWatermark(txtsname, "网站名称或域名");


            var r = sitebll.GetsiteList();


            gridControl1.DataSource = r;


            labelControl1.Text = "当前站点数量:" + r.Count();


        }




        private void simpleButton1_Click(object sender, EventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            splashScreenManager1.SetWaitFormCaption("请等待");
            splashScreenManager1.SetWaitFormDescription("加载中...");
            select();
            splashScreenManager1.CloseWaitForm();
        }

        void select()
        {
            string t = null;
            if (cstatus.Text != "状态")
            {
                t = cstatus.Text;
            }
            var r = sitebll.GetsiteList(t, txtsname.Text);
            gridControl1.DataSource = r;
            labelControl1.Text = "当前站点数量:" + r.Count();
        }
        public int Form1Value = 1;
        private void btnadd_Click(object sender, EventArgs e)
        {
            addsites f2 = new addsites();
            f2.ShowDialog(this);
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }


        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void gridControl1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //    popupMenu1.ShowPopup(Control.MousePosition);
            }
        }

        //查看详情
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            
            if (gridView1.FocusedRowHandle < 0) return;
            int selectedHandle;
            selectedHandle = this.gridView1.GetSelectedRows()[0];
            string name = this.gridView1.GetRowCellValue(selectedHandle, "name").ToString();
            string ID = this.gridView1.GetRowCellValue(selectedHandle, "ID").ToString();
            var sites=  sitebll.GetSites(ID);
            string[] csiterow = null;

            if (sites != null)
            {
                /*
                 * 获取站点信息
                 */
                try
                {
                    IISManager iismanager = new IISManager();

                    csiterow = Regex.Split(iismanager.getNewSiteInfo(sites.sname), "-@-");
                    if (csiterow != null && csiterow.Length != 1)
                    {

                        editsites f2 = new editsites(csiterow);
                        f2.ShowDialog(this);

                       
                    }
                    else if (csiterow.Length == 1)
                    {
                      

                        DevExpress.XtraEditors.XtraMessageBox.Show("未能查询到当前站点信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);


                    }
                    else
                    {
                     

                        DevExpress.XtraEditors.XtraMessageBox.Show("未能查询到当前站点信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);


                    }
                }
                catch (Exception ex)
                {
                    NLogger.Error(ex.ToString());

                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }









        }

        /// <summary>
        /// 启动 停止 站点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
         
            if (gridView1.FocusedRowHandle < 0) return;
            int selectedHandle;
            selectedHandle = this.gridView1.GetSelectedRows()[0];
            string name = this.gridView1.GetRowCellValue(selectedHandle, "name").ToString();
            string ID = this.gridView1.GetRowCellValue(selectedHandle, "ID").ToString();

             var s= sitebll.GetSites(ID);
             string al = "启用";
             if(  s.sstate== "Started")
             {
                al = "禁用";
             }

            if (DevExpress.XtraEditors.XtraMessageBox.Show("确定要"+ al + "吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                return;
            }
            else
            {
                try
                {
                    splashScreenManager1.ShowWaitForm();
                    splashScreenManager1.SetWaitFormCaption("请等待");
                    splashScreenManager1.SetWaitFormDescription("加载中...");

                    int iistouch = UtilFactory.IISTouch();
                    int errorCode = ErrorCode.siteStart;
                    AddSiteUtil addsiteUtil = new AddSiteUtil();
                    //启动站点
                    if (iistouch == 2)
                    {  
                        //iis7
                        if (al == "禁用")
                        {
                            errorCode = addsiteUtil.siteStord(name);

                        }
                        else
                        {
                            errorCode = addsiteUtil.siteStart(name);

                        }



                    }
                    if (iistouch == 1)
                    {
                        //iis6
                        if (al == "禁用")
                        {
                            errorCode = addsiteUtil.isiteStord(name);


                        }
                        else
                        {
                            errorCode = addsiteUtil.isiteStart(name);

                        }
                    }
                    if (errorCode == ErrorCode.siteStart)
                    {


                        splashScreenManager1.CloseWaitForm();
                        DevExpress.XtraEditors.XtraMessageBox.Show("操作成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                       

                    }
                    if (errorCode == ErrorCode.siteStateError)
                    {


                        splashScreenManager1.CloseWaitForm();
                        DevExpress.XtraEditors.XtraMessageBox.Show("操作失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                       

                    }


                    try
                    {

                        OpHelper.CallWithTimeout(RessiteList, 10000);

                    }
                    catch (Exception ex)
                    {
                        NLogger.Error(ex.ToString());
                        splashScreenManager1.CloseWaitForm();
                        DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }


                }

                catch (Exception ex)
                {
                    NLogger.Error("操作站点：" + ex.ToString());
                    splashScreenManager1.CloseWaitForm();
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }

         


        }
        //删除
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0) return;
            int selectedHandle;
            selectedHandle = this.gridView1.GetSelectedRows()[0];
            string id = this.gridView1.GetRowCellValue(selectedHandle, "ID").ToString();
            if (DevExpress.XtraEditors.XtraMessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                return;
            }
            else
            {
                try
                {
                    splashScreenManager1.ShowWaitForm();
                    splashScreenManager1.SetWaitFormCaption("请等待");
                    splashScreenManager1.SetWaitFormDescription("加载中...");
                    var sites = sitebll.GetSites(id);
                    //获取站点名
                    string sitename = sites.sname;
                    if (sites != null)
                    {
                        if (sites.stype == "ftp")
                        {
                            splashScreenManager1.CloseWaitForm();
                            DevExpress.XtraEditors.XtraMessageBox.Show("请手动删除FTP站点", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        else
                        {
                            
                                IISManager iismanager = new IISManager();
                                /*
                                 * 删除站点
                                 */
                                //获取站点路径
                                int errorCode = ErrorCode.Succeed;
                                string sitepath = sites.sphysicalpath;
                                string logpath = sitepath.Substring(0, 1) + @":\logs\" + sitename;
                                if (iismanager.Manager(new string[] { "REMOVESITE", sitename }, null) != ErrorCode.Succeed)
                                {
                                    //删除站点
                                    errorCode = ErrorCode.RemoveUserFail;
                                }
                                if (iismanager.Manager(new string[] { "REMOVEAPPPOOL", sitename }, null) != ErrorCode.Succeed)
                                {
                                    //删除应用池
                                    errorCode = ErrorCode.RemovePoolFail;
                                }
                                //删除文件夹权限
                                AddSiteUtil addsiteUtil = new AddSiteUtil();
                                string isitepath = sitepath;
                                if (sitepath.Contains("wwwroot"))
                                {
                                    isitepath = sitepath.Substring(0, sitepath.LastIndexOf("wwwroot"));
                                }
                                /*
                                * 获取站点根目录
                                */
                                string rootpath = sitepath;
                                if (rootpath.EndsWith("wwwroot"))
                                {
                                    string temp = rootpath.Substring(0, rootpath.LastIndexOf("wwwroot") - 1);
                                    if (!Extensions.EqualsRootPath(temp))
                                    {
                                        rootpath = temp;
                                    }
                                }
                                //addsiteUtil.icaclsReset(rootpath);
                                addsiteUtil.icaclsRemove(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + sites.sname, rootpath);
                                if (!ADUser.RemoveUser(sitename))
                                {
                                    //删除用户
                                    errorCode = ErrorCode.RemoveUserFail;
                                }
                                if (ADUser.RemoveUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + sitename))
                                {
                                    //删除应用池用户
                                    //删除用户
                                    errorCode = ErrorCode.RemoveUserFail;
                                }
                                if (!string.IsNullOrWhiteSpace(sites.ftpname))
                                {
                                    //删除FTP  
                                    iismanager.DeleteFtp(sitename);

                                    string delete_sql = " Name=@Name ";

                                    Ftpsite Ftpsite = new Ftpsite();
                                    Ftpsite.Name = sitename;
                                    Data<Ftpsite>.GetInstance().Delete("Ftpsite", delete_sql, Ftpsite);


                                }

                                try
                                {
                                    if (System.IO.Directory.Exists(sitepath))
                                    {
                                        System.IO.Directory.Delete(sitepath);//删除站点路径
                                    }
                                    if (System.IO.Directory.Exists(logpath))
                                    {
                                        System.IO.Directory.Delete(logpath);//删除日志路径
                                    }
                                }
                                catch (Exception ex)
                                {
                                    NLogger.Error(ex.ToString());
                                }
                                /*
                                 * 删除数据库记录
                                 */
                                iismanager.DeleteSite(sitename);
                            
                                splashScreenManager1.CloseWaitForm();
                                DevExpress.XtraEditors.XtraMessageBox.Show("成功删除站点", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                select();
                        }
                    }
            }
                catch (Exception ex)
            {
                NLogger.Error("删除站点：" + ex.ToString());
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }
    }
    //访问
    private void 访问站点_Click(object sender, EventArgs e)
    {
        if (gridView1.FocusedRowHandle < 0) return;
        int selectedHandle;
        selectedHandle = this.gridView1.GetSelectedRows()[0];
        string binddmoin = this.gridView1.GetRowCellValue(selectedHandle, "binddmoin").ToString();



        if (!string.IsNullOrWhiteSpace(binddmoin))
        {

            System.Diagnostics.Process.Start(@"http://" + binddmoin.Split(',')[0]);

        }

    }

    /// <summary>
    /// 安装iis
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void simpleButton2_Click(object sender, EventArgs e)
    {

        try
        {
            OpHelper.CallWithTimeout(Addmssql, 600000);
        }
        catch (Exception ex)
        {
            NLogger.Error(ex.ToString());
            splashScreenManager1.CloseWaitForm();
            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }



    }

    void Addmssql()
    {
        splashScreenManager1.ShowWaitForm();
        splashScreenManager1.SetWaitFormCaption("请等待");
        splashScreenManager1.SetWaitFormDescription("加载中...");

            if (sitebll.isiis())
            {
                splashScreenManager1.CloseWaitForm();
                DevExpress.XtraEditors.XtraMessageBox.Show("IIS已经存在了", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }
            ////else
            ////{

            //  string c = "start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-HttpRedirect;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ASP;IIS-CGI;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-ServerSideIncludes;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ODBCLogging;IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;IIS-ClientCertificateMappingAuthentication;IIS-IISCertificateMappingAuthentication;IIS-URLAuthorization;IIS-RequestFiltering;IIS-IPSecurity;IIS-Performance;IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-ManagementScriptingTools;IIS-ManagementService;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;IIS-LegacyScripts;IIS-LegacySnapIn;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI;IIS-FTPServer;IIS-FTPSvc;IIS-FTPExtensibility";

            string r = "";
        var v = Environment.OSVersion.Version.Major;

        var v2 = Environment.OSVersion.Version.Minor;
        //  MessageBox.Show(v.ToString());
        //   MessageBox.Show(v2.ToString());
        if (v >= 6 && v2 >= 2)
        {
            //   MessageBox.Show("1");
            r = sitebll.InssIIS8();//执行命令

        }
        else
        {
            r = sitebll.InssIIS7();//执行命令

        }


        if (sitebll.isiis())
        {

            splashScreenManager1.CloseWaitForm();
            DevExpress.XtraEditors.XtraMessageBox.Show("iis安装完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        else
        {
            splashScreenManager1.CloseWaitForm();
            DevExpress.XtraEditors.XtraMessageBox.Show("iis安装失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }



        ////}
    }

    /// <summary>
    /// 刷新站点 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void simpleButton3_Click(object sender, EventArgs e)
    {
        //RessiteList();

        try
        {

            OpHelper.CallWithTimeout(RessiteList, 10000);

        }
        catch (Exception ex)
        {
            NLogger.Error(ex.ToString());
            splashScreenManager1.CloseWaitForm();
            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }



    }

    void RessiteList()
    {
        txtsname.Text = "";
        cstatus.Text = "状态";
        splashScreenManager1.ShowWaitForm();
        splashScreenManager1.SetWaitFormCaption("请等待");
        splashScreenManager1.SetWaitFormDescription("加载中...");
        var r = sitebll.RessiteList();
        gridControl1.DataSource = r;

        labelControl1.Text = "当前站点数量:" + r.Count();

        splashScreenManager1.CloseWaitForm();
    }


}
}
